import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Button, Modal, Tabs, Tooltip, Form, Input, Select, message } from 'antd';
import { defaultProps } from '../schema';
import { operationOption } from './options';
import EditableTable, { IColumns } from '@inbiz/basic/EditableTable';
import { useForm } from '@formily/react';
import { useQueryFields } from '@inbiz/hooks';
import IconSettings from './IconSettings';
import FieldForm from './FieldForm';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import AuthForm, { useAuth } from '@inbiz/basic/AuthForm';
import config from './shared';
import { TextWidget, getMessage } from '@inbiz/react';

const { TabPane } = Tabs;
type IProps = {
  callBackEvents?: { [key in `on${string}`]: Function };
  emit?: (type: any, ...arg: any) => void;
  onChange?: Function;
  value?: any;
} & typeof defaultProps;
const { Option, OptGroup } = Select;

const SettingView = (props: IProps) => {
  const oldValue = props.value;
  const form = useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [activeKey, $activeKey] = useState('1');
  const oldOperations = oldValue.operations || [];
  const [fieldsForm] = Form.useForm();
  const [choosedAuth, changeHandle, generateFlag] = useAuth();
  const sourceModelUpdate= form?.query(/sourceModelUpdate$/)?.take()?.['value'];
  const sourcetype = useMemo(() => {
    if (!sourceModelUpdate) {
      return 'model';
    } else {
      return JSON.parse(sourceModelUpdate).sourcetype;
    }
  }, [sourceModelUpdate]);
  const sourceModel = form.fields?.['form.senior.soure.x-component-props.sourceModel']?.value
  //@ts-ignore
  const [fields] = useQueryFields(
    {
      key: isModalVisible
        ? sourceModel
        : undefined,
      //@ts-ignore
      appId: form.appInfo.appId,
    },
    [isModalVisible],
  );
  const IconSettingsRef = useRef(null);

  const fieldsOption: any[] = useMemo(() => {
    let newfieldsOption: any[] = [];
    if (fields && fields?.length) {
      (fields || []).forEach((item) => {
        const model = item.origin_FieldName?.split('$')[0];
        const origin = item.origin_FieldName?.split('$')[1];
        if (!newfieldsOption.find((item2) => item2.label == model)) {
          newfieldsOption.push({
            label: model,
            value: item.ModelKey,
            key: item.ModelKey,
            options: [
              {
                label: item.label,
                value: `${origin}$${item.value}`,
                key: `${origin}$${item.value}`,
              },
            ],
          });
        } else {
          newfieldsOption = newfieldsOption.map((item1) => {
            if (model == item1.label) {
              return {
                ...item1,
                options: [
                  ...item1.options,
                  {
                    label: item.label,
                    value: `${origin}$${item.value}`,
                    key: `${origin}$${item.value}`,
                  },
                ],
              };
            } else {
              return item1;
            }
          });
        }
      });
    }
    return newfieldsOption;
  }, [fields, sourcetype]);

  const formItemsRef = useRef({ formItems: props.value?.formItems });

  useEffect(() => {
    fieldsForm.setFieldsValue(oldValue.fieldRelation);
  }, [oldValue.fieldRelation]);

  const operationColumns: IColumns = useMemo(() => {
    return [
      {
        title: getMessage('Tree.operationType'),
        width: 150,
        dataIndex: 'type',
        editData: {
          type: 'Select',
          options: operationOption.map((item) => {
            item.label = getMessage(`Tree.${item.value}`);
            return item;
          }),
          afterEdit: (val, record) => {
            const selectItem = operationOption.filter((item) => {
              return item.value === val;
            })[0];
            return {
              ...record,
              name: `Tree.${selectItem.value}` || record.name || '',
            };
          },
          rules: [
            {
              required: true,
            },
          ],
        },
        render: (val, row, index) => {
          return val ? getMessage(`Tree.${val}`) : '';
        },
      },
      {
        dataIndex: 'operationflag',
        title: (
          <span>
            <span style={{ paddingRight: '10px' }}>
              {' '}
              <TextWidget>Tree.Identification</TextWidget>
            </span>
            <Tooltip title={getMessage('Tree.identificationDescription')}>
              <ExclamationCircleOutlined />
            </Tooltip>
          </span>
        ),
        isIdentical: true,
        width: 200,
        editData: {
          type: 'AutoComplete',
          rules: [],
          options: (choosedAuth?.allInfo?.Children || []).map((ele) => ({
            value: ele.ObjectValue,
            label: ele.ObjectValue + `(${getMessage(ele.ObjectName)})`,
          })),
        },
      },
      {
        title: getMessage('Tree.operationname'),
        dataIndex: 'name',
        width: 200,
        editData: {
          type: 'MultilingualInput',
          rules: [
            {
              required: true,
            },
          ],
        },
      },
      sourcetype != 'model'
        ? {
            title: '数据源',
            dataIndex: 'api',
            width: 100,
            editData: {
              type: 'ApiQuery',
              isDatasource: false,
              open: true,
              beforEdit: (record: { type: string }) => {
                return record?.type == 'delete';
              },
            },
          }
        : undefined,
      {
        title: getMessage('Tree.operationpage'),
        dataIndex: 'page',
        width: 150,
        editData: {
          type: 'PageSelect',
          beforEdit: (record: { type: string }) => {
            return record.type != 'delete';
          },
        },
      },
    ].filter((item) => !!item) as IColumns;
  }, [choosedAuth, sourcetype]);

  const getRef = () => {
    return useRef<{
      // 获取数据， 会触发校验
      getData: () => Promise<Object>;
      // 主动校验
      valid: () => Promise<Object>;
      // 更新内部数据
      updateSource: (id: string, data: object) => boolean;
    }>();
  };

  const operationTableRef = getRef();

  const showModal = () => {
    // 此处获取对应eform示例框的对应的数据
    // if (!form.fields['form.senior.soure.x-component-props.sourceModel']?.value) {
    //   message.warn(getMessage('Tree.tips.pleaseConfigureTheQueryDataSourceFirst'));
    //   return;
    // }
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    const newOperationData = await operationTableRef.current?.getData().catch((error) => {
      // 缺陷编号：36779【PC_权限】组件标识重复后点确定有两个气泡提示标识不能重复
      // operationTableRef.current?.getData();
      $activeKey('1');
      throw error;
    });
    // @ts-ignore
    const newIconData = await IconSettingsRef.current?.getValue().catch((error) => {
      error.msg && message.error(error.msg);
      // 缺陷编号：36779【PC_权限】组件标识重复后点确定有两个气泡提示标识不能重复
      // operationTableRef.current?.getData();
      $activeKey('2');
      throw error;
    });
    await fieldsForm.validateFields().catch((error) => {
      $activeKey('3');
      throw error;
    });

    const flagList = newOperationData.map((ele) => ({ value: ele.operationflag, label: ele.name }));
    await generateFlag(flagList);
    props.onChange({
      operations: newOperationData,
      IconsSettings: newIconData,
      fieldRelation: fieldsForm.getFieldsValue(true),
      // manager: manager,
      formItems: {
        ...formItemsRef.current.formItems,
      },
      auth: choosedAuth?.value,
    });
    setIsModalVisible(false);
  };

  const handleCancel = async () => {
    fieldsForm.setFieldsValue(oldValue.fieldRelation);
    $activeKey('1');
    setIsModalVisible(false);
  };

  const handleAddOperation = useCallback(() => {
    const key = Date.now();
    return { key, id: key };
  }, []);

  const changeTabs = useCallback((activeKey) => {
    $activeKey(activeKey);
  }, []);

  const filedSelect = useMemo(() => {
    if ((sourcetype === 'model' || sourcetype == '') && sourceModel) {
      return (
        <Select
        showSearch
        filterOption={(input, option) =>
         (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
       }
         style={{ width: '100%' }} optionLabelProp={'label'}>
          {fieldsOption?.map((item) => {
            return (
              <OptGroup label={item.label}>
                {item.options?.map((item1: any) => {
                  return (
                    <Option value={item1.value} key={item1.label} label={item1.label}>
                      {item1.label.indexOf('.') != -1 ? item1.label.split('.')[1] : item1.label}
                    </Option>
                  );
                })}
              </OptGroup>
            );
          })}
        </Select>
      );
    } else {
      return <Input style={{ width: '100%' }} />;
    }
  }, [sourcetype, fieldsOption]);

  return (
    <>
      <Button type="primary" onClick={showModal}>
        {getMessage('Tree.configbtn')}
      </Button>
      <Modal
        title={getMessage('Tree.configbtn')}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={900}
        destroyOnClose={true}
        okText={getMessage('global.sure')}
        cancelText={getMessage('Tree.cancel')}
        wrapClassName="inbiz-TreeSelect-modal"
        isMove
      >
        <Tabs activeKey={activeKey} onChange={changeTabs}>
          <TabPane tab={getMessage('Tree.oparetion')} key="1" forceRender={true}>
            <FieldForm
              initialValues={oldValue.formItems}
              formItemsRef={formItemsRef}
              fields={config.formItems}
              layout={(config as any).layout}
            />
            <AuthForm initialValues={props.value?.auth} onChange={changeHandle} />
            <EditableTable
              rowKey={'id'}
              columns={operationColumns}
              dataSource={oldOperations}
              deleteBtn={{ children: getMessage('Tree.delete'), danger: true }}
              scroll={{ y: 350 }}
              addBtn={{ children: getMessage('Tree.add'), type: 'primary' }}
              onAdd={handleAddOperation}
              ref={operationTableRef}
              // disableDraggable={true}
            />
          </TabPane>
          <TabPane tab={getMessage('Tree.icon')} key="2" forceRender={true}>
            <IconSettings
              isInput={sourcetype !== 'model'}
              ref={IconSettingsRef}
              value={props.value}
              fieldsOption={fieldsOption}
            />
          </TabPane>
          <TabPane tab={getMessage('Tree.condition')} key="3" forceRender={true}>
            <Form form={fieldsForm} labelCol={{ span: 6 }} wrapperCol={{ span: 8 }}>
              <Form.Item
                name="id"
                label={getMessage('Tree.nodeid')}
                required
                rules={[
                  { required: true, message: getMessage('Tree.tips.pleaseSelectAndOptionFirst') },
                ]}
              >
                {filedSelect}
              </Form.Item>
              <Form.Item
                name="label"
                label={getMessage('Tree.nodetext')}
                required
                rules={[
                  { required: true, message: getMessage('Tree.tips.pleaseSelectAndOptionFirst') },
                ]}
              >
                {filedSelect}
              </Form.Item>
              <Form.Item
                name="parentId"
                label={getMessage('Tree.parentnodeid')}
                required
                rules={[
                  { required: true, message: getMessage('Tree.tips.pleaseSelectAndOptionFirst') },
                ]}
              >
                {filedSelect}
              </Form.Item>
              <Form.Item name="rootId" label={getMessage('Tree.rootid')}>
                <Input style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item name="selectedId" label={getMessage('Tree.defaultselectid')}>
                <Input style={{ width: '100%' }} />
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Modal>
    </>
  );
};

export default SettingView;
